let wsManager = null;
$(function () {
    //获取浏览器指纹
    getBrowserFingerprint();
    if (Token.get()) {
        wsManager = WebSocketManager.getInstance(WEBSOCKET_URL, {
            heartbeat: {
                enable: true,
                interval: 30000,
                message: () => ({ // 使用函数动态获取最新值
                    cmd: WS_CMD.HEARTBEAT,
                    token: Token.get(), // 实时获取最新token
                    data: WS_CMD.HEARTBEAT,
                    signKey: Store.get("browser_fingerprint")
                })
            }
        }, function (e) {
            const detailData = {
                token: Token.get(),
                cmd: WS_CMD.CONNECT,
                signKey: Store.get("browser_fingerprint")
            };
            wsManager.send(detailData);
        });
        wsManager.onData(function (data) {
            console.log('收到消息:', data);
            handlerData(data)
        });
    }
})

function getBrowserFingerprint() {
    var userAgent = navigator.userAgent || "not available";
    var webdriver = navigator.webdriver || "not available";
    var pixelRatio = window.devicePixelRatio || "not available";
    var timezoneOffset = -(new Date).getTimezoneOffset();
    var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "not available";
    var platform = getCurrentSystem();
    var token = Token.get() || "SFT";
    var infoString = userAgent + webdriver + pixelRatio + timezoneOffset + timeZone + platform + token;
    const murmur = Fingerprint2.x64hash128(infoString, 31);
    Store.set("browser_fingerprint", murmur)
}

//获取当前浏览器操作系统平台
function getCurrentSystem() {
    var operatingInfo = navigator.userAgent;
    var isWin = (navigator.platform === "Win32") || (navigator.platform === "Windows");
    var isMac = (navigator.platform === "Mac68K") || (navigator.platform === "MacPPC") || (navigator.platform === "Macintosh") || (navigator.platform === "MacIntel");
    if (isMac) return "Mac";
    var isUnix = (navigator.platform === "X11") && !isWin && !isMac;
    if (isUnix) return "Unix";
    var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
    if (isLinux) return "Linux";
    if (isWin) {
        var isWin2K = operatingInfo.indexOf("Windows NT 5.0") > -1 || operatingInfo.indexOf("Windows 2000") > -1;
        if (isWin2K) return "Win2000";
        var isWinXP = operatingInfo.indexOf("Windows NT 5.1") > -1 || operatingInfo.indexOf("Windows XP") > -1;
        if (isWinXP) return "WinXP";
        var isWin2003 = operatingInfo.indexOf("Windows NT 5.2") > -1 || operatingInfo.indexOf("Windows 2003") > -1;
        if (isWin2003) return "Win2003";
        var isWinVista = operatingInfo.indexOf("Windows NT 6.0") > -1 || operatingInfo.indexOf("Windows Vista") > -1;
        if (isWinVista) return "WinVista";
        var isWin7 = operatingInfo.indexOf("Windows NT 6.1") > -1 || operatingInfo.indexOf("Windows 7") > -1;
        if (isWin7) return "Win7";
        var isWin10 = operatingInfo.indexOf("Windows NT 10") !== -1;
        if (isWin10) return "Win10"
    }
    return "other";
}

function getPageType() {
    const url = window.location.href;

    if (url.includes('/station/detail')) {
        return 'detail';
    } else if (url.includes('/calibration/calibration')) {
        return 'calibration';
    } else {
        return 'other';
    }
}

function handlerData(data) {
    const result = data;
    if (result.code === "00000") {
        if (WS_CMD.CONNECT_SUCCESS === result.cmd) {
            return false;
        } else {
            const type = result.type;
            let currentPageType = getPageType();
            switch (type) {
                case WS_TYPE.STATION_NOTICE:
                    if (currentPageType === 'calibration') {
                        break;
                    }
                    if (currentPageType === 'detail' && result.stationId !== stationId) {
                        break;
                    }

                    if ((currentPageType === 'detail' && result.stationId === stationId) || currentPageType === 'other') {
                        const cmdActions = {
                            [WS_CMD.MODE_CHANGE]: ["切换模式", true, WS_STATUS.SUCCESS],
                            [WS_CMD.CONF]: ["设置任务", true, WS_STATUS.SUCCESS],
                            [WS_CMD.FEED_REPORT]: ["投喂报告", true, WS_STATUS.SUCCESS],
                            [WS_CMD.STOP_STATUS]: ["设备停止", true, WS_STATUS.SUCCESS],
                            [WS_CMD.STATION_STATUS]: ["设备网络状态", false, WS_STATUS.SUCCESS],
                            [WS_CMD.TIMEOUT]: ["超时报警", false, WS_STATUS.DANGER]
                        };
                        if (result.cmd in cmdActions && result.cmd !== WS_CMD.STATE) {
                            const [title, showClose, status] = cmdActions[result.cmd];
                            ws_notice_store(title, result.message, showClose, status);
                        }
                        if (typeof detailData === 'function') {
                            detailData(result);
                            return false;
                        }
                    }
                    break;
                case WS_TYPE.CALIBRATION:
                    if (currentPageType === 'calibration') {
                        if (typeof onCaliData === 'function') {
                            onCaliData(result)
                        }
                    }
                    break;
                case WS_TYPE.AI_DIALOGUE:
                    if (typeof onDataAi === 'function') {
                        onDataAi(result)
                    }
                    break;
                default:
                    console.log("Websocket收到错误消息");
                    break;
            }
        }
    } else if (result.code === "M0004") {
        LayerUtil.failMsg("用户未授权登录或会话已过期，请重新登录")
        wsManager.close();
        setTimeout(function () {
            localStorage.clear();
            window.location.href = LOGIN_VIEW;
        }, 1000)
        return false;
    } else {
        LayerUtil.failMsg(result.msg != null ? result.msg : ERROR_MSG.FAIL)
        wsManager.close();
    }
}

function ws_notice_store(title, message, isSuccess, type) {
    if (type === null) {
        type = isSuccess ? WS_STATUS.SUCCESS : WS_STATUS.WARNING;
    }
    ws_notice(title, message, isSuccess, type);
}

function ws_notice(title, message, isSuccess, type) {
    const icon = isSuccess ? "mdi mdi-bell" : "mdi mdi-alert";
    $.notify({
        icon: icon,
        title: title + '<br>',
        message: message
    }, {
        element: '#notify-container',
        type: type,
        allow_dismiss: true,
        newest_on_top: true, //是否最新的居上
        placement: {
            from: "top",
            align: "right"
        },
        offset: 0,
        spacing: 10,
        z_index: 1031,
        delay: 5000,
        timer: 1000,
        mouse_over: 'pause',
        animate: {
            enter: 'animated fadeInDown',
            exit: 'animated fadeOutUp'
        },
        onShow: null,
        onShown: null,
        onClose: null,
        onClosed: null,
        icon_type: 'class',
        template: '<div data-notify="container" class="container_div col-md-12 alert alert-{0}" role="alert">' +
            '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
            '<span data-notify="icon"></span> ' +
            '<span data-notify="title" class="font-weight-bold">{1}</span> ' +
            '<span data-notify="message">{2}</span>' +
            '<div class="progress" data-notify="progressbar">' +
            '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
            '</div>' +
            '<a href="{3}" target="{4}" data-notify="url"></a>' +
            '</div>'
    });
    return false;
}

